<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
      class="account-form-grid"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属企业" prop="enterpriseCode" required>
            <el-select v-model="formData.enterpriseCode" placeholder="请选择所属企业" style="width: 80%">
              <el-option
                v-for="item in enterpriseList"
                :key="item.enterpriseCode"
                :label="item.enterpriseName"
                :value="item.enterpriseCode"
              />
            </el-select>
            <el-button icon="el-icon-menu" @click="openEnterpriseDialog" style="margin-left: 8px" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户账号姓名" prop="accountName" required>
            <el-input v-model="formData.accountName" placeholder="请输入客户账号姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobileNumber" required>
            <el-select v-model="formData.mobileAreaCode" placeholder="区号" style="width: 40%">
              <el-option label="中国大陆 +86" value="+86" />
              <el-option label="美国/加拿大 +1" value="+1" />
              <el-option label="中国香港 +852" value="+852" />
              <el-option label="中国台湾 +886" value="+886" />
            </el-select>
            <el-input v-model="formData.mobileNumber" placeholder="请输入手机号" style="width: 58%; margin-left:2%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="emailAddress">
            <el-input v-model="formData.emailAddress" placeholder="请输入邮箱地址" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="notes">
            <el-input
              type="textarea"
              v-model="formData.notes"
              :maxlength="140"
              show-word-limit
              placeholder="请输入备注"
              rows="4"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="是否启用" prop="isEnabled" required>
            <el-switch v-model="formData.isEnabled" active-text="ON" inactive-text="OFF" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm" :disabled="formLoading" style="background: #c6f35a; color: #fff; border: none;">保存</el-button>
    </template>
    <!-- 企业选择弹窗 -->
    <el-dialog v-model="enterpriseDialogVisible" title="选择企业" width="500px">
      <el-table :data="enterpriseList" @row-click="selectEnterprise">
        <el-table-column prop="name" label="企业名称" />
      </el-table>
    </el-dialog>
  </Dialog>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { AccountManagementApi, AccountManagementVO } from '@/api/customer/accountmanagement'

/** 客户账号管理表，用于存储和管理客户的账号信息，包括企业编号、名称、账号名称、联系方式、创建人等信息 表单 */
defineOptions({ name: 'AccountManagementForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formRef = ref() // 表单 Ref

// 企业选择相关
const enterpriseDialogVisible = ref(false)
const enterpriseList = ref([
  { enterpriseCode: '12314', enterpriseName: '智慧零售股份有限公司' },
  { enterpriseCode: 'EC0002', enterpriseName: '创新制造集团' },
])
const openEnterpriseDialog = () => {
  enterpriseDialogVisible.value = true
}
const selectEnterprise = (row: any) => {
  formData.value.enterpriseCode = String(row.enterpriseCode)
  // 选中后自动补全企业名称
  formData.value.enterpriseName = row.enterpriseName
  enterpriseDialogVisible.value = false
}

const formData = ref({
  id: undefined as number | undefined,
  enterpriseCode: '',
  enterpriseName: '',
  accountName: '',
  mobileAreaCode: '+86',
  mobileNumber: '',
  emailAddress: '',
  notes: '',
  isEnabled: true,
  creationTime: '',
  operationDescription: '',
})
const formRules = reactive({
  enterpriseCode: [{ required: true, message: '请选择所属企业', trigger: 'change' }],
  accountName: [{ required: true, message: '请输入客户账号姓名', trigger: 'blur' }],
  mobileNumber: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  isEnabled: [{ required: true, message: '请选择是否启用', trigger: 'change' }],
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '添加客户账号' : '编辑客户账号'
  formType.value = type
  // await fetchEnterpriseList?.() // 如果有接口，拉取企业列表
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      const data = await AccountManagementApi.getAccountManagement(id)
      formData.value = {
        id: data.id,
        enterpriseCode: data.enterpriseCode,
        enterpriseName: data.enterpriseName,
        accountName: data.accountName,
        mobileAreaCode: data.mobileAreaCode || '+86',
        mobileNumber: data.mobileNumber,
        emailAddress: data.emailAddress,
        notes: data.notes,
        isEnabled: data.isEnabled,
        creationTime: data.creationTime || '',
        operationDescription: data.operationDescription || '',
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    // 查找企业名称
    const selected = enterpriseList.value.find(e => e.enterpriseCode === formData.value.enterpriseCode)
    // 编辑时用已有 creationTime，新建时用当前时间
    let creationTime = formData.value.creationTime
    if (!creationTime) {
      creationTime = new Date().toISOString().slice(0, 19).replace('T', ' ')
    }
    const data: any = {
      enterpriseCode: formData.value.enterpriseCode,
      enterpriseName: selected ? selected.enterpriseName : formData.value.enterpriseName,
      accountName: formData.value.accountName,
      mobileNumber: formData.value.mobileNumber,
      emailAddress: formData.value.emailAddress,
      creationTime,
      notes: formData.value.notes,
      isEnabled: formData.value.isEnabled,
      operationDescription: formData.value.operationDescription,
    }
    if (formType.value === 'update' && formData.value.id !== undefined) {
      data.id = formData.value.id
    }
    if (formType.value === 'create') {
      await AccountManagementApi.createAccountManagement(data)
      message.success('创建成功')
    } else {
      await AccountManagementApi.updateAccountManagement(data)
      message.success('更新成功')
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    enterpriseCode: '',
    enterpriseName: '',
    accountName: '',
    mobileAreaCode: '+86',
    mobileNumber: '',
    emailAddress: '',
    notes: '',
    isEnabled: true,
    creationTime: '',
    operationDescription: '',
  }
  formRef.value?.resetFields()
}
</script>
<style scoped>
.account-form-grid {
  padding: 10px 0 0 0;
}
</style>